﻿using System;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using ReAnimation.DAL.Mapping;
using ReAnimation.Legacy.DAL;

namespace ReAnimation.DAL
{
    public class NHibernateUtil : INHibernateUtil
    {
        private static readonly ISessionFactory SessionFactory;
        private ISession _currentSession;

        static NHibernateUtil()
        {
            try
            {
                SessionFactory = 
                Fluently.Configure().Database(
                    SQLiteConfiguration
                        .Standard
                        .UsingFile("atoms.sq3")//TODO: need to be a parameter
                )
                .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                .Mappings(x => x.FluentMappings.Add(typeof(AtomDescriptionMap)).ExportTo("C:\\Temp\\"))
                .BuildSessionFactory();
            }
            catch (Exception ex)
            {
                throw new Exception("NHibernate initialization failed", ex);
            }
        }

        public ISession OpenSession()
        {
            if (_currentSession == null)
                _currentSession = SessionFactory.OpenSession();
            return _currentSession;
        }

        public void CloseSession()
        {
            if(_currentSession != null)
            {
                _currentSession.Close();
                _currentSession = null;
            }
        }
    }
}